<?php
namespace app\modules\user\behaviors;

use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use app\helpers\DatetimeHelper;

/**
 * 时间戳行为，实现了基本的时间戳补充和更新
 * @date 2020-11-25
 * @author wxw
 * 
 */
class TimestampBehavior extends Behavior{
    
    public function events()
    {
        return ArrayHelper::merge(parent::events(), [
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
        ]);
    }

    public function beforeInsert($event){
        $timeNow = DatetimeHelper::msectime();
        // $event->sender->create_timestamp = $timeNow; //和下面写法等价
        // $event->sender->update_timestamp = $timeNow;
        $this->owner->create_timestamp = $timeNow;
        $this->owner->update_timestamp = $timeNow;
    }

    public function beforeUpdate($event){
        $timeNow = DatetimeHelper::msectime();
        // $event->sender->update_timestamp = $timeNow;
        $this->owner->create_timestamp = $timeNow;
    }
}